package com.security.customer.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: TongRui乀
 * @Date: 2020/3/21 10:03
 * @description：
 */
@Slf4j
@Component("customerUsernamePasswordLoginFailureHandler")
public class CustomerUsernamePasswordLoginFailureHandler implements AuthenticationFailureHandler {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("登录失败 -- customerUsernamePasswordLoginFailureHandler m原因{}", e.getMessage());


        httpServletResponse.setContentType("application/json;charset=utf-8");


        HashMap<String, String> map = new HashMap<>();

        map.put("code", "1001");
        map.put("message", e.getMessage());

        // 这里默认返回的是json数据
        // 同时在这里也可已决定是否是跳转页面  可以通过继承 SimpleUrlAuthenticationFailureHandler 来实现非json返回的处理逻辑

        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(map));

    }
}
